
package com.ruhua.java.service;

import com.ruhua.java.dao.*;
import com.ruhua.java.dto.OrderDTO;
import com.ruhua.java.dto.SkuInfoDTO;
import com.ruhua.java.exception.ErrException;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.logic.OrderCheck;
import com.ruhua.java.repository.OrderGoodsRepository;
import com.ruhua.java.repository.OrderRepository;
import com.ruhua.java.repository.UserAddressRepository;
import com.ruhua.java.util.CommonUtil;
import com.ruhua.java.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruhua.java.util.CommonUtil.toJsonString;


@Service
public class OrderService {
    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    OrderGoodsRepository orderGoodsRepository;

    @Autowired
    UserAddressRepository userAddressRepository;

    @Autowired
    SkuService SkuService;

    @Value("${wx.order.pay-time-limit}")
    private Integer payTimeLimit;


    public OrderCheck check(OrderDTO orderDTO) {
        System.out.println("222");
        if (orderDTO.getTotalPrice().compareTo(new BigDecimal("0")) <= 0) {
            throw new TrowException("金额错误");
        }
        System.out.println("333");
        List<Long> skuIdList = orderDTO.getJson()
                .stream()
                .map(SkuInfoDTO::getSkuId)
                .collect(Collectors.toList());
        System.out.println("skuid:" + toJsonString(skuIdList));
        List<Sku> skuList = SkuService.getSkuListByIds(skuIdList);
        System.out.println("skulist:" + toJsonString(skuList));

        OrderCheck orderCheck = new OrderCheck(
                orderDTO, skuList
        );
        orderCheck.isOK();
        return orderCheck;
    }



    public Order getById(Long num) {
        return orderRepository.findOneByOrderId(num);
    }

    public Optional<Order> findByOrderId(Long id) {
        return orderRepository.findByOrderId(id);
    }

    public List<Order> MyNotPayOrder(Long id) {
        return orderRepository.findByUidAndNotPay(id);
    }

    public List<Order> MyPayOrder(Long id) {
        return orderRepository.findByUidAndPay(id);
    }

    public Optional<Order> getByName(String num) {
        return orderRepository.findByOrderNum(num);
    }

    public List<Order> findAll(){
        return orderRepository.findAll();
    }

    public void createOrderSku(Long orderId,List<Sku> skuList,Map<Long,Integer> numlist){
        skuList.forEach(s->{
            Long skuid=s.getId();
            if(!numlist.containsKey(skuid)){
                throw new TrowException("规格不存在");
            }
            Integer num=numlist.get(skuid);
            OrderGoods item=new OrderGoods(s,num,orderId);

            Long goodsId=s.getGoodsId();
            String pic=goodsService.getProPic(goodsId);
            item.setPic(pic);
            orderGoodsRepository.save(item);
        });
    }

    public Long createOrder(Long uid, OrderDTO dto) {
        if(dto.getTotalPrice().compareTo(new BigDecimal("0"))<=0){
            throw new TrowException("订单金额错误");
        }

        String orderNum = OrderUtil.makeOrderNo();   System.out.println("order:" + orderNum);
        Calendar now = Calendar.getInstance();
        Date expiredTime = CommonUtil.addSomeSeconds(now, this.payTimeLimit).getTime();
        Integer yzCode=CommonUtil.getRandom(6);
        Order item = Order.builder()
                .orderNum(orderNum)
                .userId(uid)
                .state(1)
                .yzcode(yzCode)
                .goodsMoney(dto.getTotalPrice())
                .orderMoney(dto.getTotalPrice())
                .couponId(dto.getCouponId())
                .tableNum(dto.getTableNum())
                .orderFrom(dto.getOrderFrom())
                .driveType(dto.getDriveType())
                .paymentType(dto.getPaymentType())
                .message(dto.getMsg())
                .couponMoney(0)
                .expiredTime(expiredTime)
                .build();
        if(!dto.getDriveType().equals("店内就餐")){
            item=setOrderAddress(uid,item); }
        orderRepository.save(item);return item.getOrderId();
    }

    public Order setOrderAddress(Long uid,Order item){
        Optional<UserAddress> uaddress=userAddressRepository.findByUserIdDefault(uid);
        UserAddress address=uaddress.orElseThrow(()->new ErrException("收货地址错误"));
        item.setReceiverAddress(address.getDetail());
        item.setReceiverCity(address.getProvince() + address.getCity());
        item.setReceiverMobile(address.getMobile());
        item.setReceiverName(address.getName());
        return item;
    }

    public void setSkuData(OrderDTO dto){
        List<Long> skuIdList = dto.getJson().stream().map(SkuInfoDTO::getSkuId).collect(Collectors.toList());
        List<GoodsSku> skuList = goodsService.getSkuListByIds(skuIdList);

    }

    public void updateOrderPrepayId(Long orderId, String prePayId) {
        Optional<Order> order = this.orderRepository.findByOrderId(orderId);
        order.ifPresent(o -> {
            o.setPrepayId(prePayId);
            this.orderRepository.save(o);
        });
        order.orElseThrow(() -> new NotFoundException(1005));
    }


    public void delItem(Long id) {
orderRepository.deleteById(id);

            }

}
